﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BotvaBot.Configuration.Personaj;
using BotvaBot.RequestChains;
using Helpers;
using HAP = HtmlAgilityPack;
using System.Text.RegularExpressions;
using BotvaBot.RequestChains.Base;

namespace BotvaBot
{
    public class PersonajInfo
    {
        public int Money { get; set; }
        public int Kristaly { get; set; }
        public int Pirashki { get; set; }
        public int Kapusta { get; set; }
        public int Kirka { get; set; }
        public int Kaska { get; set; }
        public int Ochki { get; set; }
        public int ZdorovieMax { get; set; }
        public int ZdorovieCurrent { get; set; }
        public int ZdorovieSpeed { get; set; }
        public int ZverMax { get; set; }
        public int ZverCurrent { get; set; }
        public int ZverSpeed { get; set; }

        protected HAP.HtmlDocument Html { get; set; }


        protected PersonajInfo()
        { }

        public PersonajInfo(string content)
        {
            Html = GetHtml(content);
        }

        public PersonajInfo(PersonajCfg personaj)
        {
            string content = GetContent(personaj);
            Html = GetHtml(content);
        }

        public PersonajInfo(PersonajCfg personaj, BotvaChainContext context)
        {
            string content = GetContent(personaj, context);
            Html = GetHtml(content);
        }



        #region Helpers

        protected string GetContent(PersonajCfg personaj)
        {
            return GetContent(personaj, null);
        }

        protected string GetContent(PersonajCfg personaj, BotvaChainContext context)
        {
            string result = null;

            GetPersonajInfoChain chain = null;
            if (context == null)
                chain = new GetPersonajInfoChain();
            else
                chain = new GetPersonajInfoChain(context);

            chain.Personaj = personaj;
            chain.RunChain();

            if (chain.IsSuccessfulyInvoked == null || (!chain.IsSuccessfulyInvoked.Value))
                return null;

            result = chain.GetPersonajPageContent();

            return result;
        }

        protected HAP.HtmlDocument GetHtml(string content)
        {
            if (StringHelper.IsnullOrBlank(content))
                throw new Exception("Personaj page content is empty");

            HAP.HtmlDocument html = new HAP.HtmlDocument();
            html.OptionFixNestedTags = true;
            html.LoadHtml(content);

            return html;
        }

        #endregion Helpers
        
        
        public PersonajInfo GetInfo()
        {
            PersonajInfo result = new PersonajInfo();

            result.Money = GetMoney();
            result.Kristaly = GetKristaly();
            result.Pirashki = GetPirashki();
            result.Kapusta = GetKapusta();
            result.Kirka = GetKirka();
            result.Kaska = GetKaska();
            result.Ochki = GetOchki();
            GetZdorovieCurrent();
            //result.ZdorovieMax = GetZdorovieMax();
            //result.ZdorovieCurrent = GetZdorovieCurrent();
            GetZverCurrent();
            //result.ZverMax = GetZverCurrent();
            //result.ZverCurrent = GetZverCurrent();

            return result;
        }

        


        public int GetMoney()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("/html/body/div/div/div/div/div[2]/div[2]/div/b");
            string sValue = node.InnerText;

            int result = Int32.Parse(sValue.Replace(".", string.Empty));
            return result;
        }

        public int GetKristaly()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("/html/body/div/div/div/div/div[2]/div[2]/div[2]/b");
            string sValue = node.InnerText;

            int result = Int32.Parse(sValue.Replace(".", string.Empty));
            return result;
        }

        public int GetPirashki()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("/html/body/div/div/div/div/div[2]/div[2]/div[3]/b");
            string sValue = node.InnerText;

            int result = Int32.Parse(sValue.Replace(".", string.Empty));
            return result;
        }

        public int GetKapusta()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("/html/body/div/div/div/div/div[2]/div[2]/div[4]/b");
            string sValue = node.InnerText;

            int result = Int32.Parse(sValue.Replace(".", string.Empty));
            return result;
        }

        public int GetKirka()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("//*[@id=\"i16\"]");
            string sValue = node.InnerText;

            int result = Int32.Parse(sValue.Replace(".", string.Empty));
            return result;
        }

        public int GetKaska()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("//*[@id=\"i18\"]");
            string sValue = node.InnerText;

            int result = Int32.Parse(sValue.Replace(".", string.Empty));
            return result;
        }

        public int GetOchki()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("//*[@id=\"i17\"]");
            string sValue = node.InnerText;

            int result = Int32.Parse(sValue.Replace(".", string.Empty));
            return result;
        }

        public int GetZdorovieMax()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("/html/body/div/div/div/div/div[3]/div[2]/div[2]/div");
            string infoText = node.InnerText;
            int splitIndex = infoText.IndexOf("ЗВЕРУШКА");
            string personajInfo = infoText.Substring(0, splitIndex);

            Regex re = new Regex("Здоровье: (?<value>[0-9]*)/(?<max>[0-9]*)");
            Match m = re.Match(personajInfo);

            int max = Int32.Parse(m.Groups["max"].Value);

            return max;
        }

        public string GetZdorovieCurrent()
        {
            HtmlAgilityPack.HtmlNode nodeChar = Html.GetElementbyId("char");
            string command = nodeChar.Attributes["onmouseover"].Value;
            string[] parts = command.Split(',');
            string parameters = parts[1];
            parameters = parameters.Substring(1, parameters.Length - 2);
            string[] results = parameters.Split(';');
            
            int now = 0;
            int max = 0;
            int speed = 0;

            foreach (string resultPair in results)
            {
                if (resultPair.ToLower().StartsWith("now"))
                {
                    string strValueNow = resultPair.Split(':').Last();
                    strValueNow = strValueNow.Substring(1, strValueNow.Length - 2);
                    if (!int.TryParse(strValueNow, out now))
                        now = 0;
                }

                if (resultPair.ToLower().StartsWith("max"))
                {
                    string strValueMax = resultPair.Split(':').Last();
                    strValueMax = strValueMax.Substring(1, strValueMax.Length - 2);
                    if (!int.TryParse(strValueMax, out max))
                        max = 0;
                }

                if (resultPair.ToLower().StartsWith("speed"))
                {
                    string strValueSpeed = resultPair.Split(':').Last();
                    strValueSpeed = strValueSpeed.Substring(1, strValueSpeed.Length - 2);
                    if (!int.TryParse(strValueSpeed, out speed))
                        speed = 0;
                }
            }

            ZdorovieCurrent = now;
            ZdorovieMax = max;
            ZdorovieSpeed = speed;

            string value = string.Format("{0} : {1} : {2}", now, max, speed);

            /*
            HtmlAgilityPack.HtmlNode node = Html.DocumentNode.SelectSingleNode("/html/body/div/div/div/div/div[3]/div[2]/div[2]/div");
            string infoText = node.InnerText;
            int splitIndex = infoText.IndexOf("ЗВЕРУШКА");
            string personajInfo = infoText.Substring(0, splitIndex);

            Regex re = new Regex("Здоровье: (?<value>[0-9]*)/(?<max>[0-9]*)");
            Match m = re.Match(personajInfo);

            int value = Int32.Parse(m.Groups["value"].Value);
            */

            return value;
        }

        public int GetZverMax()
        {
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("/html/body/div/div/div/div/div[3]/div[2]/div[2]/div");
            string infoText = node.InnerText;
            int splitIndex = infoText.IndexOf("ЗВЕРУШКА");
            string personajInfo = infoText.Substring(splitIndex);

            Regex re = new Regex("Здоровье: (?<value>[0-9]*)/(?<max>[0-9]*)");
            Match m = re.Match(personajInfo);

            int max = Int32.Parse(m.Groups["max"].Value);

            return max;
        }

        public string GetZverCurrent()
        {
            HtmlAgilityPack.HtmlNode nodePet = Html.GetElementbyId("pet");
            var nodesDiv = nodePet.Elements("div");
            var nodeDiv = nodesDiv.Last();


            string command = nodeDiv.Attributes["onmouseover"].Value;
            string[] parts = command.Split(',');
            string parameters = parts[1];
            parameters = parameters.Substring(1, parameters.Length - 2);
            string[] results = parameters.Split(';');

            int now = 0;
            int max = 0;
            int speed = 0;

            foreach (string resultPair in results)
            {
                if (resultPair.ToLower().StartsWith("now"))
                {
                    string strValueNow = resultPair.Split(':').Last();
                    strValueNow = strValueNow.Substring(1, strValueNow.Length - 2);
                    if (!int.TryParse(strValueNow, out now))
                        now = 0;
                }

                if (resultPair.ToLower().StartsWith("max"))
                {
                    string strValueMax = resultPair.Split(':').Last();
                    strValueMax = strValueMax.Substring(1, strValueMax.Length - 2);
                    if (!int.TryParse(strValueMax, out max))
                        max = 0;
                }

                if (resultPair.ToLower().StartsWith("speed"))
                {
                    string strValueSpeed = resultPair.Split(':').Last();
                    strValueSpeed = strValueSpeed.Substring(1, strValueSpeed.Length - 2);
                    if (!int.TryParse(strValueSpeed, out speed))
                        speed = 0;
                }
            }

            ZdorovieCurrent = now;
            ZdorovieMax = max;
            ZdorovieSpeed = speed;

            string value = string.Format("{0} : {1} : {2}", now, max, speed);


            //*[@id="pet"]

            /*
            HAP.HtmlNode node = Html.DocumentNode.SelectSingleNode("/html/body/div/div/div/div/div[3]/div[2]/div[2]/div");
            string infoText = node.InnerText;
            int splitIndex = infoText.IndexOf("ЗВЕРУШКА");
            string personajInfo = infoText.Substring(splitIndex);

            Regex re = new Regex("Здоровье: (?<value>[0-9]*)/(?<max>[0-9]*)");
            Match m = re.Match(personajInfo);

            int value = Int32.Parse(m.Groups["value"].Value);
            */

            return value;
        }


        public TimeSpan GetSaveTime()
        {
            var dtStart = DateTime.Now;

            int result = 0;

            string content = Html.DocumentNode.OuterHtml;

            int start = content.IndexOf("<div class='timers'>");
            int end = content.IndexOf("</div>", start);
            content = content.Substring(start, end - start);

            start = content.IndexOf("counter_3");
            start = content.IndexOf(">", start);
            end = content.IndexOf("<", start);

            content = content.Substring(start + 1, end - (start + 1));

            if (content.Contains(":"))
            {

                string[] parts = content.Split(':');
                int hours = 0;
                if (!int.TryParse(parts[0], out hours))
                    hours = 0;

                int minutes = 0;
                if (!int.TryParse(parts[1], out minutes))
                    hours = 0;

                int seconds = 0;
                if (!int.TryParse(parts[2], out seconds))
                    hours = 0;

                result = ((hours * 60 + minutes) * 60 + seconds) * 1000;
            }

            var dtEnd = DateTime.Now;

            result -= dtEnd.Subtract(dtStart).Milliseconds; 
            
            return TimeSpan.FromMilliseconds(result);
        }
    }
}
